package top.haijunit.work.core.doamin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.ToString;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;

/**
 * 统一返回Rest风格的数据结构
 *
 * @author zhanghaijun
 * @since 2024-08-07
 */
@Data
@ToString
@Schema(description = "分页数据")
public class ResultPage<T> extends Result<Collection<T>> implements java.io.Serializable {

    @Schema(description = "当前页码")
    private long page;
    @Schema(description = "每页大小")
    private long size;
    @Schema(description = "数据总条数")
    private long total;

    public static <T> ResultPage<T> of(Collection<T> data, long page, long size, long total) {
        ExceptionEnum success = ExceptionEnum.SUCCESS;
        ResultPage<T> result = new ResultPage<>();
        result.setCode(success.getCode());
        result.setMessage(success.getMessage());
        result.setData(data);
        result.setPage(page);
        result.setSize(size);
        result.setTotal(total);
        return result;
    }

    public static <E, T> ResultPage<T> build(IPage<E> page, Function<List<E>, List<T>> convert) {
        return of(convert.apply(page.getRecords()), page.getCurrent(), page.getSize(), page.getTotal());
    }
}
